package com.example.securitydemo.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @author Cary
 * @date 2022/3/25
 * cors配置
 */
@Configuration
public class CorsConfig {
    /**
     * 设置允许跨域的源
     */
    private static final String[] ORIGINS_VAL = new String[]{
            "127.0.0.1:8080",
    };

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        this.addAllowedOrigins(configuration);
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedOrigin("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    private void addAllowedOrigins(CorsConfiguration corsConfiguration) {
        for (String origin : ORIGINS_VAL) {
            corsConfiguration.addAllowedOrigin("http://" + origin);
            corsConfiguration.addAllowedOrigin("https://" + origin);
        }
    }
}
